import * as echarts from '../../components/ec-canvas/echarts';
const app = getApp();
var option_pie = null;
const option = {
  backgroundColor: "#fff",
  tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效   
          type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
  },

  legend: {
      show:false,
  },

  grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['周日', "周一", "周二", "周三", "周四", "周五", "周六"],
    axisLabel: {
       show: true,
      textStyle: {
        color: '#999999',  //更改坐标轴文字颜色
        fontSize : 14      //更改坐标轴文字大小
      }
     },
    axisLine:{
      lineStyle:{
       color:'#ededed' //更改坐标轴颜色
      }
    },
    axisTick: {
      show: false
    },
    splitLine: {
      show: false
    }
  },
  yAxis: {
      axisLine:{
        lineStyle:{
        color:'#ededed' //更改坐标轴颜色
        }
      },
      splitLine: {
        show: false
      },
      type: 'value',
			min:0,
			max:12,
			interval:2,
			axisLabel: {
				show: true,
				textStyle: {
					color:'#999999',
					fontSize: 14,
				},
				formatter: function(value){
					if(value == 0){
						return ' '
					} else {
						return value + "h"
					}
        }
      }
  },

  series: [
    {
      name: '深睡',
      type: 'bar',
      stack: '广告',
      emphasis: {
        focus: 'series'
      },
      data: [4, 2, 2, 3, 4, 2, 1],
      itemStyle:{
        normal:{color:'#986bde'}
      }
    },
    {
      name: '浅睡',
      type: 'bar',
      stack: '广告',
      emphasis: {
        focus: 'series'
      },
      data: [4, 4, 5, 3, 3,2 ,3],
      itemStyle:{
        normal:{color:'#4ebfcc'}
      }
    },
    {
      name: '清醒',
      type: 'bar',
      stack: '广告',
      emphasis: {
        focus: 'series'
      },
      data: [1, 1, 2, 3,1, 2, 3],
      //设置柱体颜色
      itemStyle:{
        normal:{color:'#37ceab'}
      }
    },
  ]

};

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr 
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

function initPie(canvas,width,height,dpr){
  option_pie = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio:dpr
  });
  canvas.setChart(option_pie);
  return option_pie;
}

Page({
  
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    //深色
    bottomColor: '#00c2cf',
    //浅色
    gradientColor:'#00d2a9',
    monitorDate:"",
    period:1,
    navList: [],
    status: 0,
    list:[0,1,2,3,4,5,6,7,8,9],
    ec:{
      onInit:initChart
    },
    ec1:{
      onInit:initPie
    },
    ellipsis:true,
    captimg:"../../assets/image/down.jpg",
    ellipsis1:true,
    captimg1:"../../assets/image/down1.jpg",
    result:false,
    isbind:false,

    heartAvg:'?',
    heartMax:'?',
    heartMin:'?',

    breathAvg:'?',
    breathMax:'?',
    breathMin:'?',

    initCode:'',
    jkheight:100,
    smheight:100,
    
    sleepData:{           // 睡眠报告
      bodyAvg:10,       //平均每分钟体动次数
      breathAvg:30,     //平均呼吸
      breathMax:40,     //最高呼吸
      breathMin:20,     //最低呼吸
      createTime:"2021-03-24 11:11:11",    //报告创建日期
      healthSuggest:"无建议",  //健康建议
      heartAvg:70,            //平均心率
      heartMax:80,            //最高心率
      heartMin:60,            //最低心率
      period:2,               //报告第几期
      sleep1:20,              //清醒
      sleep2:60,              //浅睡
      sleep3:20,              //深睡
      sleepSuggest:"无建议",   //睡眠建议
      snoringAvg:10           //打鼾
    },
    baseNum1:0,
    baseNum2:0
  },

  // 点击登录 触发获取用户信息
  // getUserInfo:function(e){
  //   console.log("eeee",e.detail)
  //   let that = this;
  //   // 获取用户信息
  //   wx.getSetting({
  //     success(res){
  //       console.log(res,"ddddd")
  //       if(res.authSetting['scope.userInfo']){
  //         console.log("授权=====");
  //         wx.getUserInfo({
  //           success(res){
  //             console.log("获取用户信息成功",res)
  //             that.setData({
  //               name:res.userInfo.nickName,
  //               head:res.userInfo.avatarUrl,
  //               result:true
  //             })

  //             wx.showTabBar({
  //               animation: true,
  //             });

  //             // 请求设备列表接口
  //             app.getToken().then(res=>{
  //               that.getDeviceList(res.token);
  //             })

  //           },

  //           fail(res){
  //             console.log("获取用户信息失败",res)
  //           }

  //         })
  //       }else{
         
  //         console.log("未授权=====");
  //       }
  //     }

  //   })

  // },


  getUserProfile:function(e){
    let that = this;
    // 获取用户信息
    wx.getUserProfile({
      desc: "获取你的昵称、头像、地区及性别", // 不写不弹提示框
      success: res => {
        console.log("获取用户信息成功",res)
        
        that.setData({
          name:res.userInfo.nickName,
          head:res.userInfo.avatarUrl,
          result:true
        })

        wx.showTabBar({
          animation: true,
        });

        // 请求设备列表接口
        app.getToken().then(res=>{
          that.getDeviceList(res.token);
        })
      },
      fail: res => {
        //拒绝授权
        wx.showToast({
          title: '您拒绝了授权',
          icon: 'none'
        })
        return;
      }

    })

  },

  ellipsis(){
    let value = !this.data.ellipsis;
    this.setData({
      ellipsis:value
    })
    if(!value){
      this.setData({
        captimg:"../../assets/image/up.jpg"
      })
    }else{
      this.setData({
        captimg:"../../assets/image/down.jpg"
      })
    }
  },

  ellipsis1(){
    let value = !this.data.ellipsis1;
    this.setData({
      ellipsis1:value
    })
    if(!value){
      this.setData({
        captimg1:"../../assets/image/up1.jpg"
      })
    }else{
      this.setData({
        captimg1:"../../assets/image/down1.jpg"
      })
    }
  },

  getStatus(e){
    console.log("切换设备=====",e)
    this.setData({ 
      status: e.currentTarget.dataset.index, 
      leftValue: e.currentTarget.dataset.index * 90 - 180,
      initCode:e.currentTarget.dataset.code
    });
    //设置全局设备编号
    app.globalData.deviceCode = e.currentTarget.dataset.code;

    //切换设备
    this.getDeviceReport(app.globalData.token)
  },

  imageLoad(e){
    this.setData({
      imgwidth:e.detail.width
    })
  },

  getMoreJK(){
		this.setData({
			jkheight:'auto'
		})
  },
  
	getMoreSM(){
		this.setData({
			smheight:'auto'
		})
	},

  onLoad: function (options) {
    let that = this;
    wx.getSystemInfo({
      success: function( res ) {
        that.setData( {
          we_width: res.windowWidth/1.8,
          we_height:res.windowHeight/3,
          img_width:res.windowWidth/1.5,
          device_width:res.windowWidth/2
        });
      }
    });

    // 自动检测是否授权登录 若是授权，则显示底部菜单栏；若是没有授权，不显示底部菜单栏，且不回显数据 显示默认的 ？号
    this.getUserData().then(data=>{
      console.log(data,"已登录")

      if(data){
        wx.showTabBar({
          animation: true,
        })
      }else{
        wx.hideTabBar({
          animation: true,
        })
      }

      // 请求设备列表接口
      app.getToken().then(res=>{
        this.getDeviceList(res.token);
      })

    })
    
  },

  // 获取设备列表
  getDeviceList(token){
    let that = this;
    wx.request({
      url: app.globalData.url+'getUserDevice',
      data:{},
      method:'GET',
      header:{
        token:token
      },
      success:function(res){
        console.log("获取用户绑定设备列表=======",res);
        if(res.data.code == 0){ //请求成功
          if(res.data.data.length>0){  //设备列表不为空时，表示已经有绑定的设备
            res.data.data.map((item,index)=>{
              if(item.userDeviceName!==null){
                item.deviceName = item.userDeviceName
              }else{
                item.deviceName = '设备'+index;
              }
            })
  
            that.setData({
              isbind:true,
              navList:res.data.data,
              initCode:res.data.data[0].deviceCode
            });
            
            //设置全局设备编号
            app.globalData.deviceCode = res.data.data[0].deviceCode;
  
            // 请求当前设备的健康报告
            that.getDeviceReport(token);

          }else{  //设备列表为空  没有绑定设备，去绑定设备
            that.setData({
              isbind:false
            })
          }

        }else{  //请求列表失败

          that.setData({
            isbind:false
          })

        }
      }
    })
  },

  //获取设备的健康报告
  getDeviceReport(token){
    let that = this;
    console.log(that.data.initCode,"当前设备编号======");
    wx.request({
      url: app.globalData.url+'getDeviceReport/'+that.data.initCode,
      data:{},
      method:'GET',
      header:{
        token:token
      },
      success:function(res){
        console.log("获取健康报告======",res);
        let report_data = res.data.data;

        if(report_data){ //判断是否有数据
          //比较心率和呼吸 与 基础数据对比
          that.getCompare(report_data);
  
          //后端回显心率、呼吸，最高，最低和平均
          that.getTiZheng(report_data);
          
          //统计清醒、浅睡、深睡所占比例
          that.getPieSleep(report_data);
  
          //打鼾次数 和 体动 回显
          that.getDaHan(report_data);
        }else{
          report_data=that.data.sleepData;
          //比较心率和呼吸 与 基础数据对比
          that.getCompare(report_data);
  
          //后端回显心率、呼吸，最高，最低和平均
          that.getTiZheng(report_data);
          
          //统计清醒、浅睡、深睡所占比例
          that.getPieSleep(report_data);
  
          //打鼾次数 和 体动 回显
          that.getDaHan(report_data);
        }

      }
    })
  },


  //自动判断是否授权，如果授权，表示已经登录，获取设备列表、报告等
  getUserData(){
    let that = this;
    return new Promise((resolve,reject)=>{
      // wx.getSetting({
      //   success(res){

      //     if(res.authSetting['scope.userInfo']){
      //       console.log('已授权');
      //       //已经授权，可以直接调用 getUserInfo 获取头像昵称
      //       wx.getUserInfo({
      //         success(res){
      //           // console.log("获取用户信息成功",res);
      //           that.setData({
      //             result:true
      //           })
      //           resolve(that.data.result)
      //         },
  
      //         fail(res){
      //           console.log("获取用户信息失败",res)
      //           that.setData({
      //             result:false
      //           })
      //           // resolve(that.data.result)
      //         }
  
      //       })

      //     }else{
  
      //       console.log("未授权")
      //       that.setData({
      //         result:false
      //       })
      //       // resolve(that.data.result)
            
      //     }
      //   }
      // })

    })
  },

  //比较心率和呼吸 与 基础数据对比
  getCompare(report_data){
    let that = this;
    that.data.navList.map(item=>{
      if(item.deviceCode == that.data.initCode){
        that.setData({
          baseNumHeart:Math.abs(report_data.heartAvg - item.baseHeart),
          baseNumBreath:Math.abs(report_data.breathAvg - item.baseBreath)
        })
        if((report_data.heartAvg - item.baseHeart)>=0){
          that.setData({
            baseNum1:1
          })
        }else{
          that.setData({
            baseNum1:-1
          })
        }

        if((report_data.breathAvg - item.baseBreath)>=0){
          that.setData({
            baseNum2:1
          })
        }else{
          that.setData({
            baseNum2:-1
          })
        }

      }
    })
            
  },

  //后端回显心率、呼吸，最高，最低和平均
  getTiZheng(report_data){
    let that = this;
    that.setData({
      monitorDate:report_data.createTime.split(" ")[0],
      period:report_data.period,
      heartAvg:report_data.heartAvg,
      heartMax:report_data.heartMax,
      heartMin:report_data.heartMin,
      breathAvg:report_data.breathAvg,
      breathMax:report_data.breathMax,
      breathMin:report_data.breathMin
    });
  },
  
  //统计清醒、浅睡、深睡所占比例
  getPieSleep(report_data){
    setTimeout(()=>{

      option_pie.setOption({
        backgroundColor:'#ffffff',
        tooltip: {
          show:false,
          trigger: 'item',
          formatter: '{b}:{d}%'
        },
        legend: {
          data: [],
          left: 'center'
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['40%', '70%'],
            label: {
              formatter: '{b}:{d}%',
              rich: {
                a: {
                  color: '#999',
                  lineHeight: 22,
                  align: 'center'
                },
                b: {
                  fontSize: 30,
                  lineHeight: 33
                },
              }
            },
            data: [
              {
                value: report_data.sleep3, 
                name: '深睡',
                itemStyle:{
                  normal:{color:'#986bde'}
                }
              },
              {
                value: report_data.sleep2, 
                name: '清醒',
                itemStyle:{
                  normal:{color:'#37ceab'}
                }
              },
              {
                value: report_data.sleep1, 
                name: '浅睡',
                itemStyle:{
                  normal:{color:'#4ebfcc'}
                }
              }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    },1500)
  },

  //打鼾次数 和 体动 回显
  getDaHan(report_data){
    let that = this;
    that.setData({
      snoringAvg:report_data.snoringAvg,
      bodyAvg:report_data.bodyAvg,
      healthSuggest:report_data.healthSuggest,
      sleepSuggest:report_data.sleepSuggest
    })
    //全局保存打鼾和体动数据  方便实时监测里用
    app.globalData.snoringAvg = report_data.snoringAvg;
    app.globalData.bodyAvg = report_data.bodyAvg;
  },


  onReady: function () {
    
  },

  onShow: function () {
    if(this.data.result){
      this.getDeviceList(app.globalData.token)
    }
  },

  onHide: function () {
    
  },

  onUnload: function () {
    
  },

  onPullDownRefresh: function () {
    
  },

  onReachBottom: function () {
    
  },

  onShareAppMessage: function () {
    
  }

})